package com.banciyuan.bcywebview.biz.detail.comment;


import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.view.dialog.ChooseDialog;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.tag.TagView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.detail.EditActivity;
import com.banciyuan.bcywebview.biz.detail.goods.GoodsBigImageActivity;
import com.banciyuan.bcywebview.biz.detail.image.CommentImageTask;
import com.banciyuan.bcywebview.biz.login.LoginActivity;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.SmoothPersonActivity;
import com.banciyuan.bcywebview.biz.report.ReportActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.regex.MatchFilterImpl;
import com.banciyuan.bcywebview.utils.regex.MyLinkfy;
import com.banciyuan.bcywebview.utils.regex.MyRegex;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.string.UnderLineUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.DetailComment;
import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.Role;
import de.greenrobot.daoexample.model.TagDetail;

public class BaseViewComment implements View.OnClickListener {
    protected TextView name;
    protected TextView time;
    protected TextView content;
    protected ImageView head;
    protected ImageView praise_iv;
    protected TextView praise_tv;
    protected TagView role_container;
    protected RelativeLayout comment_container;
    protected DetailComment detailComment;
    protected Context mContext;
    protected DetailType detailType;
    protected String mWorkAuthorUid;
    protected String mCommentAuthorUid;
    protected int position;
    protected CommentHelper mCommentDetailHelper;
    protected LinearLayout llReplyContainer;
    protected View comment_iv;
    protected ImageView comment_pic;

    protected boolean isLoading;
    protected boolean isComment;

    private TextView[] comments;
    private TextView more_comment;

    private boolean isAnimationRunning;

    public BaseViewComment(View itemView) {
        head = (ImageView) itemView.findViewById(R.id.comment_head_img);
        time = (TextView) itemView.findViewById(R.id.comment_time_tv);
        name = (TextView) itemView.findViewById(R.id.comment_name_tv);
        content = (TextView) itemView.findViewById(R.id.comment_content_tv);
        praise_iv = (ImageView) itemView.findViewById(R.id.comment_praice_iv);
        praise_tv = (TextView) itemView.findViewById(R.id.comment_praise_num_tv);
        comment_iv = itemView.findViewById(R.id.comment_reply_iv);
        comment_pic = (ImageView) itemView.findViewById(R.id.comment_pic);
        role_container = (TagView) itemView.findViewById(R.id.roles_line);
        comment_container = (RelativeLayout) itemView.findViewById(R.id.comment_container);
        llReplyContainer = (LinearLayout) itemView.findViewById(R.id.ll_reply_container);
        comments = new TextView[]{
                (TextView) itemView.findViewById(R.id.comment_one),
                (TextView) itemView.findViewById(R.id.comment_two),
                (TextView) itemView.findViewById(R.id.comment_three)};
        more_comment = (TextView) itemView.findViewById(R.id.more_comment);
    }

    public void setData(int position, final DetailComment comment, final Context context, final boolean at, DetailType detailType, boolean isComment) {
        mCommentDetailHelper = new CommentHelper(context, detailType);
        this.position = position;
        this.detailComment = comment;
        this.detailType = detailType;
        this.mContext = context;
        this.isComment = isComment;

        setHeader(comment);
        setContent(comment, context, at);
        setPic(comment, context);
        setPraise(comment, context);
        setReplys(comment, context);
        setRoles(comment);

        comment_container.setOnClickListener(this);
        head.setOnClickListener(this);
        name.setOnClickListener(this);
        praise_iv.setOnClickListener(this);
        praise_tv.setOnClickListener(this);
        comment_iv.setOnClickListener(this);
        llReplyContainer.setOnClickListener(this);
    }

    public void setCommonIds(String workAuthorUid, String commentAuthorUid) {
        this.mWorkAuthorUid = workAuthorUid;
        this.mCommentAuthorUid = commentAuthorUid;
    }

    private void setPic(final DetailComment comment, final Context mContext) {
        if (comment.getMulti() != null &&
                !comment.getMulti().isEmpty() &&
                !TextUtils.isEmpty(comment.getMulti().get(0).getPath()) &&
                StringUtil.notNullEqual(comment.getMulti().get(0).getType(), "image")) {
            comment_pic.setVisibility(View.VISIBLE);
            CommentImageTask commentImageTask = new CommentImageTask();
            final int[] point = commentImageTask.dealPic(comment.getMulti().get(0).getW(), comment.getMulti().get(0).getH(), mContext);
            LinearLayout.LayoutParams rl = new LinearLayout.LayoutParams(point[0], point[1]);
            rl.setMargins(0, UIUtils.dip2px(12, mContext), 0, UIUtils.dip2px(12, mContext));
            comment_pic.setLayoutParams(rl);
            ImageLoader.getInstance().displayImage(comment.getMulti().get(0).getPath(), comment_pic, ImageOptions.options, new SimpleImageLoadingListener() {
                @Override
                public void onLoadingComplete(final String imageUri, View view, Bitmap loadedImage) {
                    float height = loadedImage.getHeight();
                    float width = loadedImage.getWidth();
                    float target_width = point[0];
                    float target_height = point[1];
                    Matrix matrix = new Matrix();
                    matrix.postScale(target_width / width, target_height / height);
                    comment_pic.setImageMatrix(matrix);

                    //评论带图播放gif
//                    new AsyncTask<Void, File, File>() {
//                        @Override
//                        protected File doInBackground(Void... params) {
//                            if (ImageLoader.getInstance().getDiskCache().get(imageUri).exists()) {
//                                File file = ImageLoader.getInstance().getDiskCache().get(imageUri);
//                                if (StringUtil.notNullEqual(new FileTypeUtil().getFileByFile(file), "gif")) {
//                                    return file;
//                                } else {
//                                    return null;
//                                }
//                            } else {
//                                return null;
//                            }
//                        }
//
//                        @Override
//                        protected void onPostExecute(File file) {
//                            if (file != null) {
//                                try {
//                                    GifDrawable gifDrawable = new GifDrawable(file);
//                                    comment_pic.setImageDrawable(gifDrawable);
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        }
//                    }.execute();
                }
            });
            comment_pic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    List<String> slist = new ArrayList<>();
                    slist.add(comment.getMulti().get(0).getOrigin());
                    Intent intent = new Intent(mContext, GoodsBigImageActivity.class);
                    intent.putExtra("imageUrls", (Serializable) slist);
                    intent.putExtra("position", 0);
                    mContext.startActivity(intent);
                }
            });
        } else {
            comment_pic.setVisibility(View.GONE);
        }
    }

    private void setRoles(DetailComment comment) {
        if (!comment.getRoles().isEmpty()) {
            role_container.setVisibility(View.VISIBLE);
            List<TagDetail> tagDetails = new ArrayList<>();
            for (Role role : comment.getRoles()) {
                TagDetail tagDetail = new TagDetail();
                tagDetail.setTag_name(role.getType_name());
                tagDetails.add(tagDetail);
            }
            role_container.setTlist(tagDetails);
        } else {
            role_container.setVisibility(View.GONE);
        }
    }

    private void setContent(final DetailComment comment, final Context context, final boolean at) {
        int type = comment.getType();
        String tempStr = "";
        switch (type) {
            case 1:
            default:
                tempStr = Html.fromHtml(comment.getContent()).toString();
                break;
            case 2:
                tempStr = Html.fromHtml(comment.getReplyCotent() + comment.getContent()).toString();
                break;
        }
        content.setText(tempStr);
        new AsyncTask<String, Spannable, Spannable>() {
            @Override
            protected Spannable doInBackground(String... params) {
                if (at) {
                    try {
                        SpannableString spannableString = StringUtil.setAtUser(params[0], comment.getAt_users(), context);
                        MyLinkfy.addLinks(spannableString, MyRegex.plist.get(0), "bcyapp_", new MatchFilterImpl(), null);
                        return UnderLineUtil.DisUnderLine(mContext, spannableString);
                    } catch (Exception e) {
                        return new SpannableString(params[0]);
                    }
                } else {
                    return new SpannableString(params[0]);
                }
            }

            @Override
            protected void onPostExecute(Spannable spannableString) {
                content.setText(spannableString);
            }
        }.execute(tempStr);

        content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showReplyDialog();
            }
        });
        content.setMovementMethod(LinkMovementMethod.getInstance());
    }

    private void setHeader(DetailComment comment) {
        if (StringUtil.notNullStartWithUrlHead(comment.getAvatar()))
            ImageLoader.getInstance().displayImage(comment.getAvatar(), head, ImageOptions.optionHead);
        else
            head.setImageResource(R.drawable.user_pic_big);
        if (!TextUtils.isEmpty(comment.getUname())) {
            if (StringUtil.notNullEqual(mWorkAuthorUid, comment.getUid())) {
                if (isNightFlag()) {
                    name.setText(Html.fromHtml(String.format(mContext.getString(R.string.work_owner_night), comment.getUname())));
                } else {
                    name.setText(Html.fromHtml(String.format(mContext.getString(R.string.work_owner_day), comment.getUname())));
                }
            } else {
                name.setText(comment.getUname());
            }
        }
        time.setText(StringUtil.getOppositeTime(comment.getCtime()));
    }

    protected void setReplys(DetailComment comment, Context context) {
        List<DetailComment> childComments = comment.getComments();
        if (null == childComments || childComments.isEmpty()) {
            llReplyContainer.setVisibility(View.GONE);
        } else {
            llReplyContainer.setVisibility(View.VISIBLE);
            int size = childComments.size() > 3 ? 3 : childComments.size();
            int index = 0;
            for (; index < size; index++) {
                DetailComment detailComment = childComments.get(index);
                String own = StringUtil.notNullEndWith(detailComment.getUid(), mWorkAuthorUid) ? mContext.getString(R.string.own) : "";
                String pic_content = "";
                if (detailComment.getMulti() != null && !detailComment.getMulti().isEmpty()) {
                    pic_content = mContext.getString(R.string.img_content_format);
                }
                if (isNightFlag()) {
                    if (TextUtils.isEmpty(detailComment.getReplyedName())) {
                        comments[index].setText(Html.fromHtml(String.format(context.getString(R.string.single_reply_format_dark), detailComment.getUname(), own, detailComment.getContent(), pic_content)));
                    } else {
                        comments[index].setText(Html.fromHtml(String.format(context.getString(R.string.single_reply_reply_format_dark), detailComment.getUname(), own, detailComment.getReplyedName(), detailComment.getReplyCotent(), pic_content)));
                    }
                } else {
                    if (TextUtils.isEmpty(detailComment.getReplyedName())) {
                        comments[index].setText(Html.fromHtml(String.format(context.getString(R.string.single_reply_format), detailComment.getUname(), own, detailComment.getContent(), pic_content)));
                    } else {
                        comments[index].setText(Html.fromHtml(String.format(context.getString(R.string.single_reply_reply_format), detailComment.getUname(), own, detailComment.getReplyedName(), detailComment.getReplyCotent(), pic_content)));
                    }
                }

            }
            for (int j = 0; j < comments.length; j++) {
                if (index - 1 >= j) {
                    comments[j].setVisibility(View.VISIBLE);
                } else {
                    comments[j].setVisibility(View.GONE);
                }
            }
            if (comment.getComments_count() > 3) {
                more_comment.setVisibility(View.VISIBLE);
                more_comment.setText(String.format(mContext.getString(R.string.total_reply_count_format), comment.getComments_count()));
            } else {
                more_comment.setVisibility(View.GONE);
            }
        }
    }

    protected boolean isNightFlag() {
        return detailType.getTimelineType() == TimelineFactory.TIMELINE_TYPE_WRITER && !SPHelper.getBoolean(mContext, SPConstant.SPNAME_CLOSELIGHT, SPConstant.NOVEL_LIGHT, true);
    }

    protected void setPraise(DetailComment comment, Context context) {
        if (comment.getDing_num() > 0) {
            if (comment.getHave_ding()) {
                praise_iv.setImageResource(R.drawable.like_pink);
            } else {
                praise_iv.setImageResource(R.drawable.like_grey);
            }
            praise_tv.setText(String.valueOf(comment.getDing_num()));
        } else {
            praise_iv.setImageResource(R.drawable.like_grey);
            praise_tv.setText(context.getString(R.string.good));
        }
    }

    private void alertDel() {
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(mContext);
        builder.setDescString(mContext.getString(R.string.confrim_to_delete))
                .setActionString(mContext.getString(R.string.mydialog_delete))
                .setCancelString(mContext.getString(R.string.mydialog_cancel))
                .setActionClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteCommit();
                    }
                })
                .create().show();
    }

    protected void showReplyDialog() {
        View.OnClickListener deleteOnClick;
        View.OnClickListener replyOnClick;
        View.OnClickListener reportOnClick;
        View.OnClickListener copyOnClick;
        reportOnClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                doRepost();
            }
        };
        deleteOnClick = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLoading) {
                    alertDel();
                }
            }
        };

        replyOnClick = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLoading) {
                    doReply();
                }
            }
        };

        copyOnClick = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager clip = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);

                String sb = detailComment.getContent();
                sb = sb.replaceAll("<br>", "\n");
                ClipData clipData = ClipData.newPlainText("comment", sb);
                clip.setPrimaryClip(clipData);
                MyToast.show(mContext, mContext.getString(R.string.copy_complate));
            }
        };

        String lineUid = detailComment.getUid();
        if (UserDataHelper.ifLogin(mContext)) {
            if (StringUtil.notNullEqual(lineUid,
                    UserDataHelper.getInstance(mContext).getUid())) {
                setLineAuthorBuilder(replyOnClick, deleteOnClick, copyOnClick);
            } else if (StringUtil.notNullEqual(mWorkAuthorUid,
                    UserDataHelper.getInstance(mContext).getUid()) || StringUtil.notNullEqual(mCommentAuthorUid,
                    UserDataHelper.getInstance(mContext).getUid())) {
                setMainBuilder(deleteOnClick, replyOnClick, reportOnClick, copyOnClick);
            } else {
                setOtherBuilder(replyOnClick, reportOnClick, copyOnClick);
            }
        } else {
            gotoUtil.gotoAct(mContext, LoginActivity.class);
        }
    }

    //别人的评论或者回复 isComment 是否是回复
    protected void setOtherBuilder(View.OnClickListener replyOnClick, View.OnClickListener reportOnClick, View.OnClickListener copyOnClick) {
        ChooseDialog.Builder builder = new ChooseDialog.Builder(mContext);
        builder.setChooseOneString(mContext.getString(R.string.mydialog_reply))
                .setChooseOneClick(replyOnClick)
                .setChooseTwoString(mContext.getString(R.string.copy_paste))
                .setChooseTwoClick(copyOnClick)
                .setChooseThreeString(mContext.getString(R.string.report))
                .setChooseThreeClick(reportOnClick)
                .create().show();
    }

    //这篇作品是我发的，或者这条评论是我发的
    private void setMainBuilder(View.OnClickListener deleteOnClick, View.OnClickListener replyOnClick, View.OnClickListener reportOnClick, View.OnClickListener copyOnClick) {
        ChooseDialog.Builder builder = new ChooseDialog.Builder(mContext);
        builder.setChooseOneString(mContext.getString(R.string.mydialog_reply))
                .setChooseOneClick(replyOnClick)
                .setChooseTwoString(mContext.getString(R.string.copy_paste))
                .setChooseTwoClick(copyOnClick)
                .setChooseThreeString(mContext.getString(R.string.report))
                .setChooseThreeClick(reportOnClick)
                .setChooseFourString(mContext.getString(R.string.mydialog_delete))
                .setChooseFourClick(deleteOnClick)
                .create().show();
    }

    //我自己的评论
    protected void setLineAuthorBuilder(View.OnClickListener replyOnClick, View.OnClickListener deleteOnClick, View.OnClickListener copyOnClick) {
        ChooseDialog.Builder builder = new ChooseDialog.Builder(mContext);
        builder.setChooseOneString(mContext.getString(R.string.mydialog_reply))
                .setChooseOneClick(replyOnClick)
                .setChooseTwoString(mContext.getString(R.string.copy_paste))
                .setChooseTwoClick(copyOnClick)
                .setChooseThreeString(mContext.getString(R.string.mydialog_delete))
                .setChooseThreeClick(deleteOnClick)
                .create().show();
    }

    protected void deleteCommit() {
        mCommentDetailHelper.deleteCommit(detailComment.getId(), new IGetComment() {
            @Override
            public void getSucc(String json) {
                BaseObserver.getInstance().notifyWatchers(BaseObserver.DELELE_COMMENT_EVENT, position);
                isLoading = false;
            }

            @Override
            public void getFail() {
                isLoading = false;
            }
        });
    }

    protected void doRepost() {
        Intent intent = new Intent(mContext, ReportActivity.class);
        DetailDataHelper.putBaseDetailValue(intent, detailType);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, isComment ? 3 : 1);
        intent.putExtra(gotoUtil.INTENT_VALUE_TWO, detailComment.getId());
        mContext.startActivity(intent);
    }

    protected void doReply() {
        Intent intent = new Intent(mContext, EditActivity.class);
        intent.putExtra(CommentConstants.COMMENT_TYPE, 2);
        intent.putExtra(CommentConstants.UNAME, detailComment.getUname());
        intent.putExtra(CommentConstants.CONTENT, detailComment.getContent());
        intent.putExtra(CommentConstants.SHOW_CHARGE, false);
        intent.putExtra(CommentConstants.COMMENT_ID, detailComment.getId());
        intent.putExtra(CommentConstants.COMMENT_POS, position);
        DetailDataHelper.putBaseDetailValue(intent, detailType);
        ((Activity) mContext).startActivityForResult(intent, CommentConstants.GO_REPLY);
        ((Activity) mContext).overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    private void commentDoprise() {
        if (isAnimationRunning) return;
        IZanComment iZanComment = new IZanCommentImpl() {
            @Override
            public void priseSucc(String s) {
                isAnimationRunning = true;
                praise_iv.setScaleX(2f);
                praise_iv.setScaleY(2f);
                praise_iv.setImageResource(R.drawable.frame_praise);
                AnimationDrawable animationDrawable = (AnimationDrawable) praise_iv.getDrawable();
                animationDrawable.start();
                praise_iv.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        praise_iv.setScaleX(1f);
                        praise_iv.setScaleY(1f);
                        BaseObserver.getInstance().notifyWatchers(BaseObserver.LIKE_COMMENT_EVENT, position);
                        resetPraiseClick(true);
                        isAnimationRunning = false;
                    }
                }, 20 * 24);
            }

            @Override
            public void priseFail() {
                MyToast.show(mContext, mContext.getString(R.string.operation_fail));
                resetPraiseClick(true);
            }

            @Override
            public void unPriseFail() {
                MyToast.show(mContext, mContext.getString(R.string.operation_fail));
                resetPraiseClick(true);
            }

            @Override
            public void unPriseSucc(String s) {
                BaseObserver.getInstance().notifyWatchers(BaseObserver.DISLIKE_COMMENT_EVENT, position);
                resetPraiseClick(true);
            }
        };
        doZan(iZanComment);
    }

    protected void doZan(IZanComment iZanComment) {
        ZanCommentHelper zanCommentHelper = new ZanCommentHelper(iZanComment, mContext);
        if (!detailComment.getHave_ding()) {
            zanCommentHelper.doPraiseComment(detailType, detailComment.getId());
        } else {
            zanCommentHelper.unDoPraiseComment(detailType, detailComment.getId());
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.comment_container:
                showReplyDialog();
                break;
            case R.id.comment_head_img:
            case R.id.comment_name_tv:
                gotoUtil.gotoAct(mContext, SmoothPersonActivity.class, detailComment.getUid());
                break;
            case R.id.comment_praise_num_tv:
            case R.id.comment_praice_iv:
                resetPraiseClick(false);
                commentDoprise();
                break;
            case R.id.comment_reply_iv:
                doReply();
                break;
            case R.id.ll_reply_container:
                Intent intent = new Intent(mContext, DetailCommentActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, detailComment.getId());
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, detailType);
                mContext.startActivity(intent);
                break;
        }
    }

    private void resetPraiseClick(boolean resetStatus) {
        praise_iv.setClickable(resetStatus);
        praise_tv.setClickable(resetStatus);
    }
}
